/**
 * 初始化广告管理详情对话框
 */
var AppAdsInfoDlg = {
    appAdsInfoData : new FormData(),
    targetUserType: new Set()
};


/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
AppAdsInfoDlg.set = function(key, val) {
    this.appAdsInfoData.append(key, (typeof val == "undefined") ? $("#" + key).val() : val)
    return this;
}

/**
 * 收集数据
 */
AppAdsInfoDlg.collectData = function() {
    this
        .set('adName')
        .set('locType')
        .set('adType')
        .set('jumpUrl')
        .set('startTime')
        .set('sort')
        .set('endTime').set('platform', 1);
}

/**
 * 提交添加
 */
AppAdsInfoDlg.addSubmit = function() {
    this.collectData();
    if(this.targetUserType.size === 0) {
        Feng.error("请至少选择一种目标用户")
        return
    }
    let tgstr = Array.from(this.targetUserType).join(",")
    this.set("targetUserType", tgstr)
    $.ajax({
        url: Feng.ctxPath + "/appAds/add",
        dataType:'json',
        type:'POST',
        async: false,
        data: this.appAdsInfoData,
        processData : false, // 使数据不做处理
        contentType : false, // 不要设置Content-Type请求头
        success: function(data){
            console.log(data);
            if(data.code == 200){
                Feng.success("添加成功!");
            }
        },
        error:function(response){
            Feng.error(response.responseJSON.message);
        }
    });
}

$(function() {
    layui.use(['form','upload','laydate'], function(){
        let {form,upload,laydate} = layui;
        form.verify({
            empurl: function (value) {
                if(value.length > 0 && !value.startsWith("http")) {
                    return "请输入一个有效的URL地址"
                }
            }
        })
        let startEme = laydate.render({
            elem: '#startTime',
            type: 'datetime'
        })
        let endEme = laydate.render({
            elem: '#endTime',
            type: 'datetime'
        })
        var uploadInst = upload.render({
            elem: '#imgUploader',
            auto: false,
            accept: 'images',
            field: 'adImage',
            choose: function (obj) {
                let files = obj.pushFile()
                obj.preview(function (index, file, result) {
                    AppAdsInfoDlg.set('adImage', files[index])
                    $('#demo1').attr('src', result);
                })
            }
        });
        form.on('submit(adInfo)', function (data) {
            AppAdsInfoDlg.addSubmit();
        })
        form.on('checkbox(ch)', function (data) {
            if(data.elem.checked) {
                AppAdsInfoDlg.targetUserType.add(data.elem.name)
            } else {
                AppAdsInfoDlg.targetUserType.delete(data.elem.name)
            }
        })


    });

});
